﻿<head>
<link type="text/css" rel="stylesheet" href="http://s.codeproject.com/App_Themes/Std/CSS/CodeProject.min.css?dt=2.3.110329.1">

</head>
<pre>
Title:       LightInject
Author:      seesharper
Email:       bernhard.richter@gmail.com
Member ID:   2506643
Language:    C#
Platform:    Windows
Technology:  Class Library
Level:       Intermediate
Description: Shows how to create small, single file , yet functional Inversion of Control container 
Section      Platforms, Frameworks &amp; Libraries
SubSection   Libraries
License:     CPOL</pre>


<h3>
    Introduction</h3>
<p>
    Have you ever created a project that seemed to small to take on the dependency 
    of a large Ioc framework?</p>
<p>
    Wouldn&#39;t it be nice to leverage dependency injection in your libraries without 
    the need of shipping a third party binary? </p>
<p>
    This article is going to show how to create a convension based Inversion of 
    Control container using no more than 500 lines of code including the curly 
    brackets and comments.<br />
    It is going to be so tiny that users of this container don&#39;t even need to 
    reference a new assembly, they can just copy a single file into their projects 
    to start using the container.</p>
<p>
    The question is.. Can we really implement something useful in the terms of an 
    Ioc container with just 500 lines of code?&nbsp;&nbsp; </p>
<p>
    Well, I guess that depends on how we count the lines of code. Most of the code 
    has already been written for us..we just need to put the bits together.</p>
<h3>
    Background</h3>
<p>
    Before we start looking into the details, I would like to talk a little about 
    the role of the Ioc container in our libraries and how it affects the way we 
    design our classes.</p>
<p>
    We should design our classes in such a way that it does not require an Ioc 
    container at all, but at the same time makes it possible to start using a 
    container later on if manual dependency injection becomes to complex or/and 
    tidious to manage. Don&#39;t rely on a feature from a specific Ioc framework, but 
    design the classes so that we can use them without a container.</p>
<p>
    Separation of concerns is they key to such a design and each concern is 
    analogous to a dependency.&nbsp; These dependencies should be passed to the 
    consuming class using constructor injection.</p>
<p>
    As opposed to the Service Locator pattern this calls for a clean design and it 
    becomes clear to the consumer of a class what dependencies that are neeed in 
    order for the class to be functional.</p>
<p>
    In other words, don&#39;t think about the Ioc container when designing your library, 
    it can optionally come into play later if needed. </p>
<h3>
    Manual
    Dependency Injection</h3>
<p>
    Dependency injection is really as simple as passing a dependency to another 
    class. Let&#39;s take a look at this simple example</p>
<pre>
public interface IServiceA {}

public interface IServiceB { }

public class ServiceA : IServiceA {}
    
public class ServiceB : IServiceB
{
    public ServiceB(IServiceA serviceA) {}        
}
</pre>
<p>
    In order to create an instance of ServiceB we need to pass an instance of some 
    type that implements IServiceA. It is pretty obvious that we don&#39;t need an Ioc 
    framework to do this.</p>
<p>
    We can simply inject the dependency manually</p>
<pre>
ServiceB serviceB = new ServiceB(new ServiceA());
</pre>
<p>
    This design also makes it very easy to create a mock implementation to be passed 
    to the constructor during unit testing.</p>
<h3>
    Automated Dependency Injection</h3>
<p>
    Manual dependency injection can get us far, but once the object graph starts to 
    grow deeper it starts to require a lot of plumbing code just to pass those 
    dependencies around.</p>
<p>
    This is where the Ioc container comes into play and helps us out with resolving 
    dependencies we otherwise must handle ourself.</p>
<p>
    When trying to automate a manual process, in this case code generation, I always 
    try to make the generated code exactly the same as if it was done manually.</p>
<p>
    Given the previous example, how can be dynamically generate code that is exactly 
    the same as the manual version?</p>
<h3>
    Expression trees - An AST to IL</h3>
<p>
    Dynamic code generation at runtime can be done in a number of ways in the .Net 
    framework. Prior to .Net 3.5, the only way to do code generation at runtime was 
    by using System.reflection.Emit.</p>
<p>
    In .Net 2.0 the DynamicMethod was introduced and this made things a whole lot 
    simples provided that we knew how to emit IL instructions. Once you start to 
    learn about IL, it is not all that complicated, but the code needed to do the 
    simplest thing, soon becomes overwhelming.&nbsp; </p>
<p>
    On a sidenote, we should mention that Mono.Cecil is also a library that can be 
    used to dynamically create code at runtime.</p>
<p>
    In .Net 3.5, Linq was introduced and loang with it came Expression trees. This 
    actually allows us to create code at runtime without the knowledge of IL</p>
<p>
    Lets take a look at an example</p>
<pre>
NewExpression newExpression = Expression.New(typeof (ServiceA).GetConstructor(Type.EmptyTypes));
LambdaExpression lambdaExpression = Expression.Lambda&lt;Func&lt;object&gt;&gt;(newExpression);
</pre>
<p>
    What we are doing is that we fetch the parameterless constructor and use that to 
    create a <strong>NewExpression</strong>.
</p>
<p>
    The <strong>NewExpression</strong> is then passed to the LambdaExpression that 
    in turn can be compiled like this:</p>
<pre>
Func&lt;object&gt; compiledLambda = (Func&lt;object&gt;)lambdaExpression.Compile();
IServiceA instance = (IServiceA)compiledLambda();
</pre>
<p>
    The lambda is compiled into a delegate that represents the underlying dynamic 
    method that contains the generated IL.</p>
<p>
    There is actually a debug visualizer available that allows us to inspect the IL 
    from any dynamic method. </p>
<p>
    The visualizer is available from 
    <a href="http://blogs.msdn.com/b/haibo_luo/archive/2010/04/19/9998595.aspx">
    Haibo Luo&#39;s blog</a and is a very useful tool when working with dynamically 
    generated code.</p>
<p>
    We can now use this visualizer to see the generated IL bu inspecting 
    the method behind the <strong>compiledLambda</strong> variable</p>
<p>
    <img alt="" src="Debug1.jpg" /></p>
<p>
    As we can see the generated code is just a call to the constructor and hence 
    this should perform very well.</p>
<h3>
    Injecting&nbsp; dependencies</h3>
<p>
    What about services that has dependencies such as ServiceB? It takes an 
    implementation of IServiceA as a constructor argument and we need to generate 
    the code for that as well.</p>
<p>
    Using manual DI (dependency injection), we would have to write:</p>
<pre>ServiceB serviceB = new ServiceB(new ServiceA());</pre>
<p>
    The generated code should be no different. So lets take a look at how we can 
    create an expression tree to represent exactly this code.</p>
<pre>
NewExpression newExpressionA = Expression.New(typeof(ServiceA).GetConstructor(Type.EmptyTypes));            
NewExpression newExpressionB = Expression.New(typeof(ServiceB).GetConstructors().Single(),newExpressionA);                        
LambdaExpression lambdaExpression = Expression.Lambda&lt;Func&lt;object&gt;&gt;(newExpressionB);
Func&lt;object&gt; compiledLambda = (Func&lt;object&gt;)lambdaExpression.Compile();
IServiceB instance = (IServiceB)compiledLambda();</pre>
<p>
    If we take a look at the result from lambdaExpression.ToString(), we can see 
    that it is exactly the same as our manual version. Sweet.<br />
</p>
<pre> () =&gt; new ServiceB(new ServiceA())</pre>
<p>
    And if we inspect the IL from <strong>compiledLambda</strong>, we can see that 
    the IL is just what we want. No more no less</p>
<p>
    <img alt="" src="Debug2.jpg" /></p>
<p>
    It is pretty clear that we now have the tools to create a high performance ultra 
    lightweight Ioc container.
</p>
<p>
    Note: I thought I had to call it ultra lightweight since Unity claims to be 
    lightweight :)</p>
<h3>
    LightInject</h3>
<p>
    Every project needs a name and for this tiny container I have choosen the name 
    &quot;LightInject&quot;. It suggests that we are going to inject something.
    <br />
    And Light? Lets be bold and say that it symbolizes speed like in the &quot;speed of 
    light&quot; :)
</p>
<p>
    The first thing the container must handle is to create transient instances. We 
    will look into singletons and custom lifecycles later.</p>
<p>
    The first thing we will need is some kind of map that describes the relationship 
    between services and their implementations.</p>
<p>
    We will use the following structure:</p>
<pre>
ConcurrentDictionary&lt;Type, ConcurrentDictionary&lt;string, Type&gt;&gt; _implementationMap
</pre>
<p>
    The dictionary is indexed by the service type (basetype) and for each basetype 
    we keep another dictionary that holds the implementing types indexed by the 
    service name.</p>
<p>
    By default the service name is equal to the implementing type name.</p>
<p>
    Next we need som method that allows us to register new services into the service 
    container.</p>
<pre>
public void Register(Type serviceType, Type implementingType)
{
    RegisterMapping(implementingType,serviceType);
}        
</pre>
<p>
    &nbsp;</p>
<p>
    &nbsp;</p>
<p>
    Let&#39;s imagine for a minute that are developing on a small library that we want 
    to ship as a single assembly with no third party dependencies. We will of course 
    stribe to keep the code as clean and maintainable as possible and it would be 
    great if we could use an IoC container to wire up the internal dependencies of 
    our library.
</p>
<p>
    But how de we achieve that single file deployment requirement if we still want 
    to use an IoC container?</p>
<p>
    Actually there are some tricks we can use to do that and one of them is ILMerge. 
    ILMerge can take your assembly along with your assembly and make them into one. 
    This means that we can ship one assembly with our favorite IoC framework 
    embedded into the assembly. But do we really want to embed say Unity just to do 
    our internal depedency wiring?</p>
<p>
    Besides we don&#39;t really want to read 223 written pages of documentation either 
    (That is considered a book where I come from).</p>
<p>
    The purpose of this article is to demonstrate how we can create a drop-in, ultra 
    lightweight container that we can use in our projects to offer dependency 
    resolution at a low cost.</p>
<p>
    We are going to make heavy use of the stuff that is already in the .Net 
    framework and implement as little as possible ourself. Code reuse is what it is.</p>
<h3>
    Inversion of Control and dependency injection</h3>
<p>
    Before we begin to dig into the details I feel that we should clearify what 
    Inversion Of Control really means and how it relates to the dependency injection 
    pattern.</p>
<p>
    Inversion of control as a pattern/principle that basically separates the 
    creation of a dependency from its actual use.
</p>
<p>
    Dependency Injection is just a way to achieve Inversion of Control by passing in 
    the required dependencies as constructor arguments to the target class.</p>
<p>
    It is important to remember that we can do IoC perfectly well without an IoC 
    container and we should NOT design our classes in usch a way that they require 
    the use of a IoC container or even worse, a spesific IoC container 
    implementation.&nbsp; That would leave us dependant upon the container and that 
    is one tough dependency to remove after the project is started.
</p>
<p>
    In fact, we are going to start off by creating a small example that does Ioc, 
    but without the container.</p>
<h3>
&nbsp;Manual dependecy injection</h3>
<p>
    We have the following classes in our little example</p>
<pre>
public interface IServiceA {}
    
public interface IServiceB {}
    
public interface IServiceC {}
    
public class ServiceA : IServiceA
{
    public ServiceA(IServiceB serviceB){}        
}
    
public class ServiceB : IServiceB
{
    public ServiceB(IServiceC serviceC) {}        
}
    
public class ServiceC : IServiceC
{
}
</pre>
<p>
    In order to create an instance of the ServiceA class we must write the 
    following code.</p>
<pre>
ServiceA serviceA = new ServiceA(new ServiceB(new ServiceC()));
</pre>
<p>
    What we are doing here is manual injection of all the dependencies that are 
    required to create an instance of the <strong>ServiceA</strong> class.</p>
<p>
    We can see that the dependency graph can quickly grow pretty deep and we are 
    faced with a lot of work from the consumer side to create an instance of the 
    class.</p>
<p>
    We could solve this by adding a parameterless constructor to ServiceA like this:</p>
<pre>
public class ServiceA : IServiceA
{
    public ServiceA(IServiceB serviceB){}
        
    public ServiceA()
    {
        ServiceB serviceB = new ServiceB(new ServiceC());
    }
}
</pre>

<p>
    This would then create an instance of <strong>ServiceA</strong> and wire up the 
    dependencies down the graph.
</p>
<p>
    Or we could create a static method like this:</p>
<pre>
public class ServiceA : IServiceA
{
    public ServiceA(IServiceB serviceB){}
        
    public static IServiceA Create()
    {
        return new ServiceA(new ServiceB(new ServiceC()));
    }
}
</pre>


<p>
    All of these will of course work just fine, but the last two offers the 
    possibility to just go with whatever is default or provide custom 
    implementations of the dependencies. We could for instance provide mocking 
    objects during unit testing.</p>
<p>
    While it still seems pretty trivial to create such a simple graph, it can (and 
    it will) become far more comples in a real-world scenario.
    <br />
    So we want to simplify the way we wire up dependencies. Can we do that without 
    resorting to a fullblown IoC framework?
</p>
<h3>
    LightInject</h3>
<p>
    Every project needs a name and for this tiny container I have choosen the name 
    &quot;LightInject&quot;. It suggests that we are going to inject something.
    <br />
    And Light? Lets be bold and say that it symbolizes speed like in the &quot;speed of 
    light&quot; :)
</p>
<p>
    The first thing we are going to discuss is how the interfaces maps to their 
    implementing types. Most IoC containers, with the exception of Hiro, require 
    some sort of manual work to set up the mapping between interfaces and concrete 
    types. This comes in many flavours varying from custom attributes, XML (oh the 
    horror) or some sort of service registration API.</p>
<p>
    When we think about it..do we really need to tell the container about the 
    relationship between abstract and concrete classes. Haven&#39;t we done that already 
    when we wrote the classes?</p>
<pre>
public class ServiceA : IServiceA
</pre>



<p>
    It feels almost stupid being forced to duplicate this mapping in an XML file in 
    order for the container to realize that ServiceA implements IServiceA, wouldn&#39;t 
    you say?</p>
<p>
    We are simply going to create a function that looks at an assembly and builds 
    this mapping based on the already stated relationship between interfaces and 
    classes.</p>
<p>
    Lets build an implementation map.</p>
<p>
    This is actually the first line of code in the container implementation.</p>
<pre>
private readonly ConcurrentDictionary&lt;Type, Dictionary&lt;string, Type&gt;&gt; _implementationMap =
            new ConcurrentDictionary&lt;Type, Dictionary&lt;string, Type&gt;&gt;();
</pre>
<p>
    This dictionary is indexed by the interface type where the value is another 
    dictionary where the key is the implementing type name and the value is the 
    implementing type.</p>
<p>
    Wext we need a method that takes an assembly and builds this implementation map.</p>
<pre>
public void LoadFrom(Assembly assembly)
{
    IEnumerable&lt;Type&gt; types = GetConcreteTypes(assembly);
    foreach (var type in types)
        BuildImplementationMap(type);
    _isLoaded = true;
}
</pre>





<p>
    So now we basically have all the information needed to start resolving service 
    instances.</p>
<h3>
    Factories</h3>
<p>
    The idea behind this container is to use Expression trees to dynamically build 
    the code that is needed to create a service instance.<br />
    </p>
<pre>
private Expression CreateNewExpression(Type concreteType)
{            
    ConstructorInfo constructorInfo = GetConstructorInfo(concreteType);
    IEnumerable<Expression> parameterExpressions = GetParameterExpressions(constructorInfo);
    NewExpression newExpression = Expression.New(constructorInfo, parameterExpressions);
    return newExpression;
}
</pre>







<p>
   This Expression is now wrapped by a Lambda Expression so it can be compiled and 
    resued the next time the same service type is requested.
</p>
<p>
    The next time this service type is requested, the code needed to create the 
    instance has been precompiled and executes with very good performance.</p>
<p>
    So what about services that requires dependencies to be passed in? Like for 
    instance the ServiceA class that needs an IServiceB implementation.</p>
<p>
    The CreateNewExpresssion method will recursively create the NewExpression 
    instances needed to create the instance.
</p>
<p>
    So if we was to get an instance of IServiceA, this is the code that gets 
    generated.</p>
<pre>
new ServiceA(new ServiceB(new ServiceC()))
</pre>








<p>
    As we can see this is exactly the same code as we would have written ourself to 
    inject the dependencies.</p>









